import Router from 'koa-router';
import database from '../db.js';
import { convertToProxyUrl } from '../utils/imageUtils.js';
import { authMiddleware } from '../middleware/auth.js';
import axios from 'axios';

const router = new Router({
  prefix: '/api'
});

// 获取电影列表
router.get('/movies', async (ctx) => {
  try {
    const { page = 1, pageSize = 12, category = '' } = ctx.query;

    const result = await database.getMovies(page, pageSize, category);
    // 处理每个电影的图片URL
    result.movies = result.movies.map(movie => ({
      ...movie,
      poster: convertToProxyUrl(movie.poster)
    }));
    ctx.body = result;
  } catch (error) {
    console.error('获取电影列表失败:', error);
    ctx.status = 500;
    ctx.body = { error: '获取电影数据失败' };
  }
});

// 添加新电影
router.post('/movies', authMiddleware, async (ctx) => {
  try {
    const movieData = {
      id: Date.now().toString(),
      ...ctx.request.body
    };
    await database.addMovie(movieData);
    ctx.body = { message: '电影添加成功', movie: movieData };
  } catch (error) {
    console.error('添加电影失败:', error);
    ctx.status = 500;
    ctx.body = { error: '添加电影失败' };
  }
});

// 更新电影信息
router.put('/movies/:id', authMiddleware, async (ctx) => {
  try {
    const { id } = ctx.params;
    const movieData = ctx.request.body;
    await database.updateMovie(id, movieData);
    ctx.body = { message: '电影更新成功' };
  } catch (error) {
    console.error('更新电影失败:', error);
    ctx.status = 500;
    ctx.body = { error: '更新电影失败' };
  }
});

// 删除电影
router.delete('/movies/:id', authMiddleware, async (ctx) => {
  try {
    const { id } = ctx.params;
    await database.deleteMovie(id);
    ctx.body = { message: '电影删除成功' };
  } catch (error) {
    console.error('删除电影失败:', error);
    ctx.status = 500;
    ctx.body = { error: '删除电影失败' };
  }
});

// 管理员登录
router.post('/auth/login', async (ctx) => {
  try {
    const { username, password } = ctx.request.body;
    const token = await database.authenticateAdmin(username, password);
    if (token) {
      ctx.body = { token };
    } else {
      ctx.status = 401;
      ctx.body = { error: '用户名或密码错误' };
    }
  } catch (error) {
    console.error('登录失败:', error);
    ctx.status = 500;
    ctx.body = { error: '登录失败' };
  }
});

// 图片代理
router.get('/proxy-image', async (ctx) => {
  try {
    const { url } = ctx.query;
    if (!url) {
      ctx.status = 400;
      ctx.body = { error: '缺少图片URL参数' };
      return;
    }

    const response = await axios.get(url, {
      responseType: 'arraybuffer'
    });

    ctx.set('Content-Type', response.headers['content-type']);
    ctx.body = response.data;
  } catch (error) {
    console.error('图片代理请求失败:', error);
    ctx.status = 500;
    ctx.body = { error: '获取图片失败' };
  }
});

export default router;
